<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    Mage
 * @package     Mage_Adminhtml
 * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */

/**
 * Adminhtml entity sets controller
 *
 * @category   Mage
 * @package    Mage_Adminhtml
 * @author      Magento Core Team <core@magentocommerce.com>
 */

class Mage_Adminhtml_Catalog_Product_SetController extends Mage_Adminhtml_Controller_Action
{
    function createAttributeSet($name, $attrs)
    {
        $objModel = Mage::getModel('eav/entity_setup', 'core_setup');
        $categoryName = $name;
        try {
            $catId = $objModel->getAttributeSetId('catalog_product', $categoryName);
        } catch (Exception $e) {
            $catId = False;
        }
        $attrs = json_decode($attrs, true);
        $attrSet = Mage::getModel('eav/entity_attribute_set');
        if ($catId) {
            $attrSet->load($catId);
        }
        else {
            $attrSet->setAttributeSetName($categoryName);
            $attrSet->setEntityTypeId(4); //You can look into the db what '4' corresponds to, I think it is for products.
            $attrSet->save();
        }
        $attrSet->initFromSkeleton($objModel->getAttributeSetId('catalog_product', 'По умолчанию'));
        $attrSet->save();
        foreach ($attrs as $attrId) {
            $attributeSetId = $objModel->getAttributeSetId('catalog_product', $categoryName);
            $attributeGroupId = $objModel->getAttributeGroupId('catalog_product', $attributeSetId, 'General');
            $objModel->addAttributeToSet('catalog_product', $attributeSetId, $attributeGroupId, $attrId);
        }
        return $objModel->getAttributeSetId('catalog_product', $categoryName);
    }

    function createAttribute($labelText, $attributeCode, $values = -1, $productTypes = -1, $setInfo = -1)
    {
        $attribute=Mage::getModel('eav/entity_attribute')->loadByCode(4, $attributeCode);
        $labelText = trim($labelText);
        $attributeCode = trim($attributeCode);

        if ($labelText == '' || $attributeCode == '') {
            $this->logError("Can't import the attribute with an empty label or code.  LABEL= [$labelText]  CODE= [$attributeCode]");
            return false;
        }

        if ($values === -1)
            $values = array();

        if ($productTypes === -1)
            $productTypes = array();

        if ($setInfo !== -1 && (isset($setInfo['SetID']) == false || isset($setInfo['GroupID']) == false)) {
            $this->logError("Please provide both the set-ID and the group-ID of the attribute-set if you'd like to subscribe to one.");
            return false;
        }

        $this->logInfo("Creating attribute [$labelText] with code [$attributeCode].");

        //>>>> Build the data structure that will define the attribute. See
        //     Mage_Adminhtml_Catalog_Product_AttributeController::saveAction().

        $data = array(
            'is_global' => '0',
            'frontend_input' => 'text',
            'default_value_text' => '',
            'default_value_yesno' => '0',
            'default_value_date' => '',
            'default_value_textarea' => '',
            'is_unique' => '0',
            'is_required' => '0',
            'frontend_class' => '',
            'is_searchable' => '1',
            'is_visible_in_advanced_search' => '1',
            'is_comparable' => '1',
            'is_used_for_promo_rules' => '0',
            'is_html_allowed_on_front' => '1',
            'is_visible_on_front' => '0',
            'used_in_product_listing' => '0',
            'used_for_sort_by' => '0',
            'is_configurable' => '0',
            'is_filterable' => '0',
            'is_filterable_in_search' => '0',
            'backend_type' => 'varchar',
            'default_value' => '',
        );

        // Now, overlay the incoming values on to the defaults.
        foreach ($values as $key => $newValue)
            if (isset($data[$key]) == false) {
                $this->logError("Attribute feature [$key] is not valid.");
                return false;
            }

            else
                $data[$key] = $newValue;

        // Valid product types: simple, grouped, configurable, virtual, bundle, downloadable, giftcard
        $data['apply_to'] = $productTypes;
        $data['attribute_code'] = $attributeCode;
        $data['frontend_label'] = array(
            0 => $labelText,
            1 => '',
            3 => '',
            2 => '',
            4 => '',
        );

        //<<<<

        //>>>> Build the model.

        $model = Mage::getModel('catalog/resource_eav_attribute');

        $model->addData($data);

        if ($setInfo !== -1) {
            $model->setAttributeSetId($setInfo['SetID']);
            $model->setAttributeGroupId($setInfo['GroupID']);
        }

        $entityTypeID = Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId();
        $model->setEntityTypeId($entityTypeID);

        $model->setIsUserDefined(1);

        //<<<<

        // Save.

        try
        {
            $model->save();
        }
        catch (Exception $ex)
        {
            $this->logError("Attribute [$labelText] could not be saved: " . $ex->getMessage());
            return false;
        }

        $id = $model->getId();

        $this->logInfo("Attribute [$labelText] has been saved as ID ($id).");

        return $id;
    }

    function createProduct($id, $sku,$attr_set_id,$name,$desc,$short_descr,$price,$qty,$data)
    {
        $productId = $id;
        $product = Mage::getModel('catalog/product')->load($productId);
        if (!$product) {
            $product = new Mage_Catalog_Model_Product();
        }
        // Build the product
        $product->setSku($sku);
        $product->setAttributeSetId($attr_set_id);
        $product->setTypeId('simple');
        $product->setName($name);
        #		$product->setCategoryIds(array(7)); # some cat id's, my is 7
        $product->setWebsiteIDs(array(1)); # Website id, my is 1 (default frontend)
        $product->setDescription($desc);
        $product->setShortDescription($short_descr);
        $product->setPrice($price);
        //Default Magento attribute
        $product->setWeight(99.0000);
        $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
        $product->setStatus(0);
        $product->setTaxClassId(0); # My default tax class
        $product->setStockData(array(
                                    'is_in_stock' => 1,
                                    'qty' => $qty
                               ));
        $product->setCreatedAt(strtotime('now'));
        $data = json_decode($data, true);
        foreach ($data as $attrName => $attrValue) {
            $product->setData($attrName, $attrValue);
        }
        try {
            $product->save();
        }
        catch (Exception $ex) {
            var_dump($ex);
        }
    }

    public function indexAction()
    {
        $this->_title($this->__('Catalog'))
                ->_title($this->__('Attributes'))
                ->_title($this->__('Manage Attribute Sets'));
        if ($this->getRequest()->getParam('import') == 'set') {

            print_r($this->createAttributeSet($this->getRequest()->getParam('name'),$this->getRequest()->getParam('attrs')));
        }
        elseif ($this->getRequest()->getParam('import') == 'product') {
            print_r($this->createProduct($this->getRequest()->getParam('id'),$this->getRequest()->getParam('sku'),
$this->getRequest()->getParam('attr_set_id'),$this->getRequest()->getParam('name'),$this->getRequest()->getParam('desc'),
$this->getRequest()->getParam('short_desc'),$this->getRequest()->getParam('price'),$this->getRequest()->getParam('qty'),
$this->getRequest()->getParam('data')));

        }
        elseif ($this->getRequest()->getParam('import') == 'attr') {
            print_r($this->createAttribute($this->getRequest()->getParam('label'),$this->getRequest()->getParam('code'),$this->getRequest()->getParam('value')));
        }


        else {

            $this->_setTypeId();

            $this->loadLayout();
            $this->_setActiveMenu('catalog/sets');

            $this->_addBreadcrumb(Mage::helper('catalog')->__('Catalog'), Mage::helper('catalog')->__('Catalog'));
            $this->_addBreadcrumb(
                Mage::helper('catalog')->__('Manage Attribute Sets'),
                Mage::helper('catalog')->__('Manage Attribute Sets'));

            $this->_addContent($this->getLayout()->createBlock('adminhtml/catalog_product_attribute_set_toolbar_main'));
            $this->_addContent($this->getLayout()->createBlock('adminhtml/catalog_product_attribute_set_grid'));

            $this->renderLayout();
        }
    }

    public function editAction()
    {
        $this->_title($this->__('Catalog'))
                ->_title($this->__('Attributes'))
                ->_title($this->__('Manage Attribute Sets'));

        $this->_setTypeId();
        $attributeSet = Mage::getModel('eav/entity_attribute_set')
                ->load($this->getRequest()->getParam('id'));

        if (!$attributeSet->getId()) {
            $this->_redirect('*/*/index');
            return;
        }

        $this->_title($attributeSet->getId() ? $attributeSet->getAttributeSetName() : $this->__('New Set'));

        Mage::register('current_attribute_set', $attributeSet);

        $this->loadLayout();
        $this->_setActiveMenu('catalog/sets');
        $this->getLayout()->getBlock('head')->setCanLoadExtJs(true);

        $this->_addBreadcrumb(Mage::helper('catalog')->__('Catalog'), Mage::helper('catalog')->__('Catalog'));
        $this->_addBreadcrumb(
            Mage::helper('catalog')->__('Manage Product Sets'),
            Mage::helper('catalog')->__('Manage Product Sets'));

        $this->_addContent($this->getLayout()->createBlock('adminhtml/catalog_product_attribute_set_main'));

        $this->renderLayout();
    }

    public function setGridAction()
    {
        $this->_setTypeId();
        $this->getResponse()->setBody(
            $this->getLayout()
                    ->createBlock('adminhtml/catalog_product_attribute_set_grid')
                    ->toHtml());
    }

    /**
     * Save attribute set action
     *
     * [POST] Create attribute set from another set and redirect to edit page
     * [AJAX] Save attribute set data
     *
     */
    public function saveAction()
    {
        $entityTypeId = $this->_getEntityTypeId();
        $hasError = false;
        $attributeSetId = $this->getRequest()->getParam('id', false);
        $isNewSet = $this->getRequest()->getParam('gotoEdit', false) == '1';

        /* @var $model Mage_Eav_Model_Entity_Attribute_Set */
        $model = Mage::getModel('eav/entity_attribute_set')
                ->setEntityTypeId($entityTypeId);

        /** @var $helper Mage_Adminhtml_Helper_Data */
        $helper = Mage::helper('adminhtml');

        try {
            if ($isNewSet) {
                //filter html tags
                $name = $helper->stripTags($this->getRequest()->getParam('attribute_set_name'));
                $model->setAttributeSetName(trim($name));
            } else {
                if ($attributeSetId) {
                    $model->load($attributeSetId);
                }
                if (!$model->getId()) {
                    Mage::throwException(Mage::helper('catalog')->__('This attribute set no longer exists.'));
                }
                $data = Mage::helper('core')->jsonDecode($this->getRequest()->getPost('data'));

                //filter html tags
                $data['attribute_set_name'] = $helper->stripTags($data['attribute_set_name']);

                $model->organizeData($data);
            }

            $model->validate();
            if ($isNewSet) {
                $model->save();
                $model->initFromSkeleton($this->getRequest()->getParam('skeleton_set'));
            }
            $model->save();
            $this->_getSession()->addSuccess(Mage::helper('catalog')->__('The attribute set has been saved.'));
        } catch (Mage_Core_Exception $e) {
            $this->_getSession()->addError($e->getMessage());
            $hasError = true;
        } catch (Exception $e) {
            $this->_getSession()->addException($e,
                                               Mage::helper('catalog')->__('An error occurred while saving the attribute set.'));
            $hasError = true;
        }

        if ($isNewSet) {
            if ($hasError) {
                $this->_redirect('*/*/add');
            } else {
                $this->_redirect('*/*/edit', array('id' => $model->getId()));
            }
        } else {
            $response = array();
            if ($hasError) {
                $this->_initLayoutMessages('adminhtml/session');
                $response['error'] = 1;
                $response['message'] = $this->getLayout()->getMessagesBlock()->getGroupedHtml();
            } else {
                $response['error'] = 0;
                $response['url'] = $this->getUrl('*/*/');
            }
            $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
        }
    }

    public function addAction()
    {
        $this->_title($this->__('Catalog'))
                ->_title($this->__('Attributes'))
                ->_title($this->__('Manage Attribute Sets'))
                ->_title($this->__('New Set'));

        $this->_setTypeId();

        $this->loadLayout();
        $this->_setActiveMenu('catalog/sets');

        $this->_addContent($this->getLayout()->createBlock('adminhtml/catalog_product_attribute_set_toolbar_add'));

        $this->renderLayout();
    }

    public function deleteAction()
    {
        $setId = $this->getRequest()->getParam('id');
        try {
            Mage::getModel('eav/entity_attribute_set')
                    ->setId($setId)
                    ->delete();

            $this->_getSession()->addSuccess($this->__('The attribute set has been removed.'));
            $this->getResponse()->setRedirect($this->getUrl('*/*/'));
        } catch (Exception $e) {
            $this->_getSession()->addError($this->__('An error occurred while deleting this set.'));
            $this->_redirectReferer();
        }
    }

    /**
     * Define in register catalog_product entity type code as entityType
     *
     */
    protected function _setTypeId()
    {
        Mage::register('entityType',
                       Mage::getModel('catalog/product')->getResource()->getTypeId());
    }

    protected function _isAllowed()
    {
        return Mage::getSingleton('admin/session')->isAllowed('catalog/attributes/sets');
    }

    /**
     * Retrieve catalog product entity type id
     *
     * @return int
     */
    protected function _getEntityTypeId()
    {
        if (is_null(Mage::registry('entityType'))) {
            $this->_setTypeId();
        }
        return Mage::registry('entityType');
    }
}